package io.github.lingalone.monsterauth.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Created with IntelliJ IDEA.
 *
 * @author <a href="https://github.com/lingalone">lingalone</a>
 * @version 1.0.0
 * @link
 * @since 2018/7/24
 */

public class AuthProvider implements AuthenticationProvider {

    final private Logger logger = LoggerFactory.getLogger(getClass());

    private UserDetailsService userDetailsService;
    private PasswordEncoder passwordEncoder;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();

        UserDetails userDetails = null;

        if(username !=null) {
            userDetails = userDetailsService.loadUserByUsername(username);
        }

        if(userDetails == null) {
            throw new UsernameNotFoundException("用户名/密码无效");
        }

        else if (!userDetails.isEnabled()){
            throw new DisabledException("用户已被禁用");
        }else if (!userDetails.isAccountNonExpired()) {
            throw new LockedException("账号已过期");
        }else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException("账号已被锁定");
        }else if (!userDetails.isCredentialsNonExpired()) {
            throw new LockedException("凭证已过期");
        }

        String password = userDetails.getPassword();
        logger.error(passwordEncoder.encode(password));
        logger.error(authentication.getCredentials().toString());

//        if(! passwordEncoder.matches(authentication.getCredentials().toString(), password)) {
//            throw new BadCredentialsException("账号名或密码不正确");
//        }
        //授权
        return new UsernamePasswordAuthenticationToken(userDetails, password,userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.equals(authentication);
    }
}
